package com.lee.starter.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author Lee
 * @date 2020/4/2
 */
public class FileUtils {

    /**
     * 获取文本文件内容（不适合读取大文件）
     *
     * @param file 可读的文本文件
     * @return 所有内容
     */
    public static String txt2String(File file) {
        StringBuilder result = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            String s;
            while ((s = br.readLine()) != null) {
                result.append(System.lineSeparator()).append(s);
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    public interface ReadLineCallBack {
        /**
         * 读取到每行后的回调
         *
         * @param lineStr 每行数据
         */
        void afterReadLine(String lineStr);
    }

    /**
     * 逐行读取文件内容，并将读取的内容交给回调函数处理（适合读取大文件）
     *
     * @param file     可读的文本文件
     * @param callBack 读取到每行后的回调
     */
    public static void readLine(File file, ReadLineCallBack callBack) {
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            String s;
            while ((s = br.readLine()) != null) {
                callBack.afterReadLine(s);
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存远程文件到本地，以地址最后‘/’后的名称作为文件名（通常用于下载图片或文档）
     *
     * @param uri       资源地址
     * @param localPath 本地目录
     */
    public static void saveUri2Local(String uri, String localPath) {
        FileOutputStream fos = null;
        BufferedInputStream bis = null;
        HttpURLConnection httpUrl = null;
        URL url = null;
        final int bufferSize = 1024;
        byte[] buf = new byte[bufferSize];
        int size = 0;
        try {
            url = new URL(uri);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            bis = new BufferedInputStream(httpUrl.getInputStream());
            if (!localPath.endsWith("/") && localPath.endsWith("\\")) {
                localPath += "/";
            }
            File dir = new File(localPath);
            if (!dir.exists()) {
                if (!dir.mkdirs()) {
                    throw new Exception("创建目录失败：" + localPath);
                }
            }
            String fileName = uri.substring(uri.lastIndexOf("/") + 1);
            File file = new File(localPath + fileName);
            System.out.println("保存文件：" + file.getAbsolutePath());
            fos = new FileOutputStream(file);
            while ((size = bis.read(buf)) != -1) {
                fos.write(buf, 0, size);
            }
            fos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
                if (bis != null) {
                    bis.close();
                }
                if (httpUrl != null) {
                    httpUrl.disconnect();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
